package com.jck.ws.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory;

import lombok.extern.log4j.Log4j;

/**
 * WebSocket 配置
 */
@Configuration
@EnableWebSocketMessageBroker//注解表示开启使用STOMP协议来传输基于代理的消息，Broker就是代理的意思。 
@Log4j
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

	@Override
	public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
//		通过此链接接入消息推送通道
		stompEndpointRegistry.addEndpoint("/any-socket").setAllowedOrigins("*").withSockJS(); //这一行代码用来注册STOMP协议节点，同时指定使用SockJS协
		
		//允许使用socketJs方式访问，访问点为hello，允许跨域
//        stompEndpointRegistry.addEndpoint("/hello").setAllowedOrigins("*").withSockJS();
	}

	@Override
	public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
		//全局使用的订阅前缀（客户端订阅路径上会体现出来），客户端向系统发送消息
		messageBrokerRegistry.setApplicationDestinationPrefixes("/app");//这个前缀不需要与web项目名相同，可以自己随意指定
//		  订阅Broker名称，分别表示在客户端上主题和个人的消息订阅
		messageBrokerRegistry.enableSimpleBroker("/topic", "/queue");//这里配置了两个前缀，若是destination以这两个前缀开头，则会转发给该Broker
		//点对点使用的订阅前缀（客户端订阅路径上会体现出来），不设置的话，默认也是/user/
        //registry.setUserDestinationPrefix("/user/");
		
	}

	@Override
	public void configureWebSocketTransport(final WebSocketTransportRegistration registration) {
		registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
			@Override
			public WebSocketHandler decorate(final WebSocketHandler handler) {
				return new WebSocketHandlerDecorator(handler) {
					@Override
					public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
						String username = session.getPrincipal().getName();
						log.info("online: " + username);
						super.afterConnectionEstablished(session);
					}

					@Override
					public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus)
							throws Exception {
						String username = session.getPrincipal().getName();
						log.info("offline: " + username);
						super.afterConnectionClosed(session, closeStatus);
					}
				};
			}
		});
		super.configureWebSocketTransport(registration);
	}

}
